import Vue from 'vue'
import Router from 'vue-router'

// 导入组件 Login ./表示上一目录，这里是src下，../表示上上级目录
import Login from './components/Login.vue'
import Home from './components/Home.vue'
import Welcome from '@/components/Welcome'
import Users from './components/user/Users.vue'
import Rights from './components/power/Rights.vue'
import Roles from './components/power/Roles.vue'
import Cate from './components/goods/Cate.vue'
import Params from './components/goods/Params.vue'
import GoodsList from './components/goods/List.vue'
import Add from './components/goods/Add.vue'
import Report from './components/report/Report.vue'


//导入全局样式表
import './assets/css/global.css'

//导入第三方图标库，这里导入阿里图标库
import './assets/fonts/iconfont.css'

import axios from 'axios'
// 配置请求的根路径
axios.defaults.baseURL = 'http://127.0.0.1:8888/api/private/v1/'
// axios请求拦截
axios.interceptors.request.use(config  => {
  //为请求头对象，添加token验证的Authorization字段
  config.headers.Authorization = window.sessionStorage.getItem('token');
  return config
})
// 挂载到vue的原型对象上,让每个this对象都可以通过Vue组件直接访问到$http，从而去发起请求
Vue.prototype.$http = axios

Vue.use(Router)

const routers = new Router({
  routes: [
    //定义路由规则，当用户访问path这个路径时，指定要展示的组件
    { path: '/', redirect: '/login' },
    { path: '/login', component: Login },
    // 将Welcom组件作为Home子组件
    { 
      path: '/home', 
      component: Home,
      // 访问Home组件重定向到Welcome组件  
      redirect: '/welcome',
      children: [
        {path: '/welcome',component: Welcome},
        {path: '/users', component: Users},
        {path: '/rights', component: Rights},
        {path: '/roles', component: Roles},
        { path: '/categories', component: Cate },
        { path: '/params', component: Params },
        { path: '/goods', component: GoodsList },
        { path: '/goods/add', component: Add },
        { path: '/reports', component: Report },
      ]
    },
  ]
})
// 挂载路由导航守卫
routers.beforeEach((to, from, next) => {
  // to表示将要访问的路径
  // from表示从哪个路径中来
  // next 是一个函数，表示放行，next("/login")强制跳转到登录页面
  if (to.path === '/login') return next();
  // 获取token
  const token = window.sessionStorage.getItem('token');
  // token为空，则强制跳转到登录页面
  if (!token) return next('/login');
  //不为空，则放行
  next();
})
// 导出路由导航守卫
export default routers

